﻿'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('=== testInteractionFlow 开始 ===');
  console.log('1. 接收参数:', event);
  
  try {
    const { userId, postId, postTitle, receiverId } = event;
    
    if (!userId || !postId || !receiverId) {
      return {
        code: 400,
        msg: '参数缺失',
        data: { userId, postId, receiverId }
      };
    }
    
    console.log('2. 开始测试完整流程...');
    
    // 步骤1：模拟点赞
    console.log('2.1 模拟点赞...');
    const likeRes = await db.collection('user-likes').add({
      data: {
        user_id: userId,
        post_id: postId,
        create_time: Date.now()
      }
    });
    console.log('2.1 点赞结果:', likeRes);
    
    // 步骤2：调用createMessageNotification
    console.log('2.2 调用createMessageNotification...');
    const messageRes = await uniCloud.callFunction({
      name: 'createMessageNotification',
      data: {
        type: 'like',
        postId: postId,
        postTitle: postTitle || '测试帖子',
        senderId: userId,
        receiverId: receiverId
      }
    });
    console.log('2.2 createMessageNotification结果:', messageRes);
    
    // 步骤3：查询interaction-messages表
    console.log('2.3 查询interaction-messages表...');
    const queryRes = await db.collection('interaction-messages')
      .where({ receiver_id: receiverId })
      .orderBy('create_time', 'desc')
      .limit(5)
      .get();
    console.log('2.3 查询结果:', queryRes);
    
    // 步骤4：查询user-likes表
    console.log('2.4 查询user-likes表...');
    const likesRes = await db.collection('user-likes')
      .where({ user_id: userId, post_id: postId })
      .get();
    console.log('2.4 user-likes查询结果:', likesRes);
    
    return {
      code: 200,
      msg: '测试完成',
      data: {
        likeResult: likeRes,
        messageResult: messageRes,
        interactionMessages: queryRes.data,
        userLikes: likesRes.data,
        summary: {
          likeCount: likesRes.data.length,
          messageCount: queryRes.data.length
        }
      }
    };
    
  } catch (error) {
    console.error('❌ testInteractionFlow 异常:', error);
    return {
      code: 500,
      msg: '测试失败: ' + error.message,
      error: error
    };
  }
};
